/*
 * Copyright 2020-2021 redragon.dongbin
 *
 * This file is part of redragon-erp/赤龙ERP.

 * redragon-erp/赤龙ERP is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.

 * redragon-erp/赤龙ERP is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.

 * You should have received a copy of the GNU General Public License
 * along with redragon-erp/赤龙ERP.  If not, see <https://www.gnu.org/licenses/>.
 */
package com.erp.prod.wip.controller;

import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.apache.commons.lang.StringUtils;
import org.hibernate.exception.ConstraintViolationException;
import org.redragon.framework.hibernate.data.RDDataBox;
import org.redragon.framework.hibernate.model.Pages;
import org.redragon.framework.springmvc.ControllerSupport;
import org.redragon.framework.util.ShiroUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.erp.cux.workflow.controller.CuxControllerSupport;
import com.erp.dataset.service.DatasetCommonService;
import com.erp.hr.dao.model.HrStaffInfoRO;
import com.erp.hr.service.HrCommonService;
import com.erp.masterdata.common.service.MasterDataCommonService;
import com.erp.masterdata.material.dao.model.MdMaterial;
import com.erp.prod.bom.dao.model.ProdBomHead;
import com.erp.prod.bom.service.ProdBomHeadService;
import com.erp.prod.bom.service.ProdBomLineService;
import com.erp.prod.craft.dao.model.ProdWorkCraft;
import com.erp.prod.craft.service.ProdWorkCraftProcedureService;
import com.erp.prod.craft.service.ProdWorkCraftService;
import com.erp.prod.wip.dao.data.DataBox;
import com.erp.prod.wip.dao.model.ProdWipTask;
import com.erp.prod.wip.dao.model.ProdWipTaskCO;
import com.erp.prod.wip.service.ProdWipTaskService;
import com.erp.prod.workcenter.service.ProdWorkCenterService;

@Controller
@RequestMapping("/web/prodWipTask")
public class ProdWipTaskWebController extends CuxControllerSupport{
    
    //日志处理
    private Logger logger = LoggerFactory.getLogger(ProdWipTaskWebController.class);
    
    //服务层注入
    @Autowired
    private ProdWipTaskService prodWipTaskService;
    @Autowired
    private ProdWorkCraftService prodWorkCraftService;
    @Autowired
    private ProdWorkCraftProcedureService prodWorkCraftProcedureService;
    @Autowired
    private ProdWorkCenterService prodWorkCenterService;
    @Autowired
    private ProdBomHeadService prodBomHeadService;
    @Autowired
    private ProdBomLineService prodBomLineService;
    @Autowired
    private DatasetCommonService datasetCommonService;
    @Autowired
    private MasterDataCommonService masterDataCommonService;
    @Autowired
    private HrCommonService hrCommonService;
    
    @Override
    public String getExceptionRedirectUrl() {
        return this.getFormatRedirectUrl("getProdWipTaskList");
    }
    
    
    
    /**
     * 
     * @description 查询数据列表
     * @date 2020-12-07 20:41:06
     * @author 
     * @param pages
     * @param prodWipTaskCO
     * @param model
     * @return String
     *
     */
    @RequestMapping("getProdWipTaskList")
    public String getProdWipTaskList(Pages pages, ProdWipTaskCO prodWipTaskCO, Model model) {
        //分页查询数据
        if(pages.getPage()==0) {
            pages.setPage(1);
        }
        
        //分页查询数据
        List<ProdWipTask> prodWipTaskList = this.prodWipTaskService.getDataObjectsForDataAuth("", pages, prodWipTaskCO);
        
        //循环设置职员和组织信息
        for(ProdWipTask prodWipTask: prodWipTaskList) {
            prodWipTask.setStaffName(this.hrCommonService.getHrStaff(prodWipTask.getStaffCode()).getStaffName());
            prodWipTask.setDepartmentName(this.hrCommonService.getHrDepartment(prodWipTask.getDepartmentCode()).getDepartmentName());
        }
        
        //获取物料
        Map materialMap = this.masterDataCommonService.getMaterialForMaterialMap();
        //数据状态
        Map statusMap = RDDataBox.getStatusMap();
        //审批状态
        Map approveStatusMap = RDDataBox.getApproveStatusMap();
        //任务类型
        Map taskTypeMap = DataBox.getTaskTypeMap();
        //任务状态
        Map taskStatusMap = DataBox.getTaskStatusMap();
        
        //页面属性设置
        model.addAttribute("prodWipTaskList", prodWipTaskList);
        model.addAttribute("pages", pages);
        model.addAttribute("materialMap", materialMap);
        model.addAttribute("approveStatusMap", approveStatusMap);
        model.addAttribute("taskTypeMap", taskTypeMap);
        model.addAttribute("taskStatusMap", taskStatusMap);
        model.addAttribute("statusMap", statusMap);
        //工作流属性
        this.setWorkflowModel(model, "WIP");
        
        return "basic.jsp?content=prodWipTask/prodWipTaskList";
    }
    
    
    
    /**
     * 
     * @description 查询单条数据
     * @date 2020-12-07 20:41:06
     * @author 
     * @param prodWipTask
     * @param model
     * @return String
     *
     */
    @RequestMapping("getProdWipTask")
    public String getProdWipTask(ProdWipTask prodWipTask, Model model) {
        //查询要编辑的数据
        if(prodWipTask!=null&&StringUtils.isNotBlank(prodWipTask.getTaskCode())) {
            ProdWipTask prodWipTaskTemp = this.prodWipTaskService.getDataObject(prodWipTask.getTaskCode());
            if(prodWipTaskTemp!=null) {
                prodWipTask = prodWipTaskTemp;
            }
            //获取物料信息
            MdMaterial mdMaterial = this.masterDataCommonService.getMdMaterialInfoCache(prodWipTask.getMaterialCode());
            prodWipTask.setMaterialStandard(mdMaterial.getStandard());
            
            //设置显示字段
            prodWipTask.setStaffName(this.hrCommonService.getHrStaff(prodWipTask.getStaffCode()).getStaffName());
            prodWipTask.setDepartmentName(this.hrCommonService.getHrDepartment(prodWipTask.getDepartmentCode()).getDepartmentName());
            
            //获取bom信息
            ProdBomHead prodBomHead = this.prodBomHeadService.getProdBomHeadByMaterialCode(prodWipTask.getMaterialCode());
            if(prodBomHead!=null) {
                prodWipTask.setBomHeadCode(prodBomHead.getBomHeadCode());
                prodWipTask.setBomVersion(prodBomHead.getBomVersion());
                prodWipTask.setBomHeadName(this.masterDataCommonService.getMaterialMap().get(prodBomHead.getMaterialCode())+"物料清单");
            }
            
            //获取工艺路线信息
            ProdWorkCraft prodWorkCraft = this.prodWorkCraftService.getProdWorkCraftByMaterialCode(prodWipTask.getMaterialCode());
            if(prodWorkCraft!=null) {
                prodWipTask.setCraftCode(prodWorkCraft.getCraftCode());
                prodWipTask.setCraftName(prodWorkCraft.getCraftName());
                prodWipTask.setCraftVersion(prodWorkCraft.getCraftVersion());
            }
        }else {
            prodWipTask.setTaskStatus("NOASSIGN");
            prodWipTask.setStatus("NEW");
            
            //获取当前用户职员信息
            HrStaffInfoRO staffInfo = this.hrCommonService.getStaffInfo(ShiroUtil.getPrincipal());
            prodWipTask.setStaffCode(staffInfo.getStaffCode());
            prodWipTask.setDepartmentCode(staffInfo.getDepartmentCode());
            prodWipTask.setStaffName(staffInfo.getStaffName());
            prodWipTask.setDepartmentName(staffInfo.getDepartmentName());
        }
        
        //获取物料
        Map materialMap = this.masterDataCommonService.getMaterialForMaterialMap();
        //物料单位
        Map materialUnitMap = this.datasetCommonService.getMaterialUnit();
        //数据状态
        Map statusMap = RDDataBox.getStatusMap();
        //审批状态
        Map approveStatusMap = RDDataBox.getApproveStatusMap();
        //任务类型
        Map taskTypeMap = DataBox.getTaskTypeMap();
        //任务状态
        Map taskStatusMap = DataBox.getTaskStatusMap();
        
        //页面属性设置
        model.addAttribute("prodWipTask", prodWipTask);
        model.addAttribute("approveStatusMap", approveStatusMap);
        model.addAttribute("materialMap", materialMap);
        model.addAttribute("taskTypeMap", taskTypeMap);
        model.addAttribute("taskStatusMap", taskStatusMap);
        model.addAttribute("materialUnitMap", materialUnitMap);
        model.addAttribute("statusMap", statusMap);
        //工作流属性
        this.setWorkflowModel(model, "WIP", prodWipTask.getTaskCode());
        
        return "basic.jsp?content=prodWipTask/prodWipTaskEdit";
    }
    
    
    
    /**
     * 
     * @description 编辑数据
     * @date 2020-12-07 20:41:06
     * @author 
     * @param prodWipTask
     * @param bindingResult
     * @param model
     * @return String
     *
     */
    @RequestMapping("editProdWipTask")
    public String editProdWipTask(@Valid ProdWipTask prodWipTask, BindingResult bindingResult, Model model, RedirectAttributes attr) {
        //参数校验
        Map<String, String> errorMap = this.validateParameters(bindingResult, model);
        if(errorMap.size()>0) {
            return "forward:getProdWipTask";
        }
        
        try {
            //对当前编辑的对象初始化默认的字段
            
            //保存编辑的数据
            this.prodWipTaskService.insertOrUpdateDataObject(prodWipTask);
            //提示信息
            attr.addFlashAttribute("hint", "success");
            attr.addAttribute("taskCode", prodWipTask.getTaskCode());
        }catch(Exception e){
            if(e.getCause().getClass()==ConstraintViolationException.class) {
                //提示信息
                attr.addFlashAttribute("hint", "hint");
                attr.addFlashAttribute("alertMessage", "任务编码已存在，请重新输入");
                return "redirect:getProdWipTaskList";
            }else {
                throw e;
            }
        }
        
        return "redirect:getProdWipTask";
    }
    
    
    
    /**
     * 
     * @description 删除数据
     * @date 2020-12-07 20:41:06
     * @author 
     * @param prodWipTask
     * @return String
     *
     */
    @RequestMapping("deleteProdWipTask")
    public String deleteProdWipTask(ProdWipTask prodWipTask, RedirectAttributes attr) {
        //删除数据前验证数据
        if(prodWipTask!=null&&prodWipTask.getTaskId()!=null&&StringUtils.isNotBlank(prodWipTask.getTaskCode())) {
            if(prodWipTask.getStatus().equals("NEW")) {
                //删除数据
                this.prodWipTaskService.deleteDataObject(prodWipTask);
                //提示信息
                attr.addFlashAttribute("hint", "success");
            }else {
                //提示信息
                attr.addFlashAttribute("hint", "hint");
                attr.addFlashAttribute("alertMessage", "非新建状态的生产任务不能删除");
            }
        }
        
        return "redirect:getProdWipTaskList";
    }
    
    
    
    /**
     * 
     * @description 更新审批状态
     * @date 2020年8月4日
     * @author dongbin
     * @param code
     * @param approveStatus
     * @param attr
     * @return
     * @return String
     *
     */
    @RequestMapping("updateApproveStatus")
    public String updateApproveStatus(String code, String approveStatus, RedirectAttributes attr) {
        
        if(StringUtils.isNotBlank(code)&&StringUtils.isNotBlank(approveStatus)) {
            //更新审核状态
            this.prodWipTaskService.updateApproveStatus(code, approveStatus);
            //提示信息
            attr.addFlashAttribute("hint", "success");
            attr.addAttribute("taskCode", code);
        }else {
            //提示信息
            attr.addFlashAttribute("hint", "hint");
            attr.addFlashAttribute("alertMessage", "提交或审批数据错误");
            attr.addAttribute("taskCode", code);
        }
        
        return "redirect:getProdWipTask";
    }
    
    
    
    @RequestMapping("updateTaskStatus")
    public String updateTaskStatus(String code, String taskStatus, RedirectAttributes attr) {
        
        if(StringUtils.isNotBlank(code)&&StringUtils.isNotBlank(taskStatus)) {
            //更新审核状态
            this.prodWipTaskService.updateTaskStatus(code, taskStatus);
            //提示信息
            attr.addFlashAttribute("hint", "success");
            attr.addAttribute("taskCode", code);
        }else {
            //提示信息
            attr.addFlashAttribute("hint", "hint");
            attr.addFlashAttribute("alertMessage", "任务状态修改错误");
            attr.addAttribute("taskCode", code);
        }
        
        return "redirect:getProdWipTask";
    }
    
    
    
    /**
     * 
     * @description 获取bom物料信息
     * @date 2020年11月15日
     * @author dongbin
     * @param materialCode
     * @return
     * @return String
     *
     */
    @RequestMapping("getMaterialBomAjax")
    @ResponseBody
    public String getMaterialBomAjax(String materialCode) {
        String bomHeadCode = "";
        String bomVersion = "";
        String materialName = "";
        
        try {
            //获取bom信息
            ProdBomHead prodBomHead = this.prodBomHeadService.getProdBomHeadByMaterialCode(materialCode);
            
            materialName = this.masterDataCommonService.getMaterialMap().get(prodBomHead.getMaterialCode());
            bomHeadCode = prodBomHead.getBomHeadCode();
            bomVersion = prodBomHead.getBomVersion();
        }catch(Exception e) {
            
        }
        
        return "{\"bomHeadCode\": \""+bomHeadCode+"\", \"bomVersion\": \""+bomVersion+"\", \"materialName\": \""+materialName+"\"}";
    }
    
    
    
    /**
     * 
     * @description 获取bom物料信息
     * @date 2020年11月15日
     * @author dongbin
     * @param materialCode
     * @return
     * @return String
     *
     */
    @RequestMapping("getMaterialCraftAjax")
    @ResponseBody
    public String getMaterialCraftAjax(String materialCode) {
        String craftCode = "";
        String craftName = "";
        String craftVersion = "";
        
        try {
            //获取工艺路线信息
            ProdWorkCraft prodWorkCraft = this.prodWorkCraftService.getProdWorkCraftByMaterialCode(materialCode);
            
            craftCode = prodWorkCraft.getCraftCode();
            craftName = prodWorkCraft.getCraftName();
            craftVersion = prodWorkCraft.getCraftVersion();
        }catch(Exception e) {
            
        }
        
        return "{\"craftCode\": \""+craftCode+"\", \"craftName\": \""+craftName+"\", \"craftVersion\":\""+craftVersion+"\"}";
    }
}
